<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'

// 定义props
const props = defineProps({
  scheduleEditData: {
    type: Object as () => Schedule | null,
    default: null
  }
})

// 定义数据结构
interface Event {
  eventID: number
  eventName: string
}

interface Game {
  game_name: string
  games_id: number
  events: Event[]
}

interface Schedule {
  schId: number
  schName: string
  schTime?: string
  gameId: number
  eventId: number
  state?: string
  rank?: number
}

// 格式化日期时间以适配datetime-local输入框
const formatDateTimeForInput = (dateString: string | undefined): string | undefined => {
  if (!dateString) return undefined
  
  // 创建Date对象并格式化为本地时间
  const date = new Date(dateString);
  // 获取本地时间的年月日时分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 格式化从datetime-local输入框获取的日期时间，转换为正确的ISO格式
const formatInputDateTime = (dateString: string | undefined): string | undefined => {
  if (!dateString) return undefined
  
  // datetime-local 返回的是本地时间格式，我们需要将其转换为ISO格式的UTC时间
  const date = new Date(dateString);
  return date.toISOString();
}

// 响应式数据
const games = ref<Game[]>([])
const selectedGame = ref<number | ''>('')
const selectedEvent = ref<number | ''>('')
const isEditMode = ref(false)
const currentScheduleId = ref<number | null>(null)

// 新增表单数据
const scheduleForm = ref({
  schName: '',
  schTime: '',
  state: '未开始', // 添加状态字段，默认值为"未开始"
  rank: null as number | null // 添加轮次字段
})

// 计算属性：过滤后的项目列表
const filteredEvents = ref<Event[]>([])

// 状态选项
const stateOptions = [
  { label: '未开始', value: '未开始' },
  { label: '进行中', value: '进行中' },
  { label: '已结束', value: '已结束' }
]

// 获取数据
const fetchScheduleData = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8080/event/gamesEvents', {
      headers: {
        token: token || ''
      }
    })
    
    if (response.data.success) {
      games.value = response.data.data
    }
  } catch (error) {
    console.error('获取赛程数据失败:', error)
  }
}

// 当选择的比赛改变时，更新项目列表
const onGameChange = () => {
  // 清空已选择的项目
  selectedEvent.value = ''
  
  // 更新项目列表
  if (selectedGame.value !== '') {
    const game = games.value.find(g => g.games_id === selectedGame.value)
    if (game) {
      filteredEvents.value = game.events
    }
  } else {
    filteredEvents.value = []
  }
}

// 提交表单
const submitForm = async () => {
  if (!selectedGame.value || !selectedEvent.value) {
    alert('请选择比赛和项目')
    return
  }
  
  if (!scheduleForm.value.schName) {
    alert('请输入赛程名称')
    return
  }
  
  if (!scheduleForm.value.schTime) {
    alert('请选择赛程时间')
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    if (isEditMode.value && currentScheduleId.value) {
      // 编辑模式 - PUT 请求
      const response = await axios.put('http://localhost:8080/schedule/update', {
        schId: currentScheduleId.value,
        gameId: selectedGame.value,
        eventId: selectedEvent.value,
        schName: scheduleForm.value.schName,
        schTime: formatInputDateTime(scheduleForm.value.schTime),
        state: scheduleForm.value.state,
        rank: scheduleForm.value.rank
      }, {
        headers: {
          'Content-Type': 'application/json',
          token: token || ''
        }
      })
      
      if (response.data.success || response.status === 200) {
        alert('赛程更新成功')
        // 清空表单
        scheduleForm.value.schName = ''
        scheduleForm.value.schTime = ''
        scheduleForm.value.state = '未开始'
        scheduleForm.value.rank = null
        selectedGame.value = ''
        selectedEvent.value = ''
        $emit('cancel')
      } else {
        alert('赛程更新失败: ' + (response.data.message || '未知错误'))
      }
    } else {
      // 新增模式 - POST 请求
      const response = await axios.post('http://localhost:8080/schedule/add', {
        gameId: selectedGame.value,
        eventId: selectedEvent.value,
        schName: scheduleForm.value.schName,
        schTime: formatInputDateTime(scheduleForm.value.schTime),
        state: scheduleForm.value.state, // 添加状态字段
        rank: scheduleForm.value.rank // 添加轮次字段
      }, {
        headers: {
          token: token || ''
      }})
      
      // 修改判断逻辑，不仅仅依赖 response.data.success
      if (response.data.success || response.status === 200) {
        alert('赛程添加成功')
        // 清空表单
        scheduleForm.value.schName = ''
        scheduleForm.value.schTime = ''
        scheduleForm.value.state = '未开始' // 重置状态为默认值
        scheduleForm.value.rank = null // 重置轮次为默认值
      } else {
        alert('赛程添加失败: ' + (response.data.message || '未知错误'))
      }
    }
  } catch (error: any) {
    console.error('操作赛程失败:', error)
    alert('操作赛程失败: ' + (error.response?.data?.message || error.message || ''))
  }
}

// 初始化编辑模式
const initEdit = (schedule: Schedule) => {
  isEditMode.value = true
  currentScheduleId.value = schedule.schId
  scheduleForm.value.schName = schedule.schName
  scheduleForm.value.schTime = formatDateTimeForInput(schedule.schTime) || ''
  scheduleForm.value.state = schedule.state || '未开始'
  scheduleForm.value.rank = schedule.rank !== undefined ? schedule.rank : null
  selectedGame.value = schedule.gameId
  selectedEvent.value = schedule.eventId
  
  // 确保数据加载完成后再更新项目列表
  const updateEvents = () => {
    // 查找对应的游戏数据
    const game = games.value.find(g => g.games_id === schedule.gameId)
    if (game) {
      filteredEvents.value = game.events
      // 确保选中的项目在列表中
      const eventExists = game.events.some(e => e.eventID === schedule.eventId)
      if (!eventExists) {
        selectedEvent.value = ''
      }
    } else {
      filteredEvents.value = []
      selectedEvent.value = ''
    }
  }
  
  // 如果数据已经加载完成，直接更新；否则等待数据加载完成
  if (games.value.length > 0) {
    updateEvents()
  } else {
    // 等待数据加载完成
    const interval = setInterval(() => {
      if (games.value.length > 0) {
        clearInterval(interval)
        updateEvents()
      }
    }, 100)
    
    // 设置超时时间，避免无限等待
    setTimeout(() => {
      clearInterval(interval)
    }, 5000)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchScheduleData().then(() => {
    // 检查是否有编辑数据
    if (props.scheduleEditData) {
      initEdit(props.scheduleEditData as Schedule)
    }
  })
})

// 监听游戏选择变化
watch(selectedGame, () => {
  onGameChange()
})

// 监听编辑数据变化
watch(() => props.scheduleEditData, (newVal) => {
  if (newVal) {
    initEdit(newVal as Schedule)
  } else {
    // 重置为新增模式
    isEditMode.value = false
    currentScheduleId.value = null
    scheduleForm.value.schName = ''
    scheduleForm.value.schTime = ''
    scheduleForm.value.state = '未开始'
    scheduleForm.value.rank = null
    selectedGame.value = ''
    selectedEvent.value = ''
  }
})

// 定义事件发射
const $emit = defineEmits(['cancel'])
</script>

<template>
  <div class="new-schedule-container">
    <h2>{{ isEditMode ? '编辑赛程' : '新建赛程' }}</h2>
    
    <div class="form-section">
      <div class="form-item">
        <label for="game-select">选择比赛：</label>
        <select 
          id="game-select" 
          v-model="selectedGame" 
          @change="onGameChange"
          class="form-select"
          required
        >
          <option value="">请选择比赛</option>
          <option 
            v-for="game in games" 
            :key="game.games_id" 
            :value="game.games_id"
          >
            {{ game.game_name }}
          </option>
        </select>
      </div>
      
      <div class="form-item">
        <label for="event-select">选择项目：</label>
        <select 
          id="event-select" 
          v-model="selectedEvent" 
          :disabled="!selectedGame"
          class="form-select"
          required
        >
          <option value="">请选择项目</option>
          <option 
            v-for="event in filteredEvents" 
            :key="event.eventID" 
            :value="event.eventID"
          >
            {{ event.eventName }}
          </option>
        </select>
      </div>
      
      <!-- 添加名称文本框 -->
      <div class="form-item">
        <label for="schName">赛程名称：</label>
        <input 
          type="text" 
          id="schName" 
          v-model="scheduleForm.schName" 
          class="form-input"
          placeholder="请输入赛程名称"
        />
      </div>
      
      <!-- 添加日期选择器 -->
      <div class="form-item">
        <label for="schTime">赛程时间：</label>
        <input 
          type="datetime-local" 
          id="schTime" 
          v-model="scheduleForm.schTime" 
          class="form-input"
        />
      </div>
      
      <!-- 添加状态选择下拉列表 -->
      <div class="form-item">
        <label for="state">赛程状态：</label>
        <select 
          id="state" 
          v-model="scheduleForm.state" 
          class="form-select"
        >
          <option 
            v-for="option in stateOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </option>
        </select>
      </div>
      
      <!-- 添加轮次输入框 -->
      <div class="form-item">
        <label for="rank">轮次：</label>
        <input 
          type="number" 
          id="rank" 
          v-model.number="scheduleForm.rank" 
          class="form-input"
          placeholder="请输入轮次(可选)"
        />
      </div>
      
      <div class="form-actions">
        <button class="submit-btn" @click="submitForm">{{ isEditMode ? '更新' : '提交' }}</button>
        <button class="cancel-btn" @click="$emit('cancel')">取消</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.new-schedule-container {
  width: 100%;
  padding: 20px;
}

.new-schedule-container h2 {
  text-align: center;
  color: #31B310;
  margin-bottom: 30px;
}

.form-section {
  max-width: 600px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.form-item label {
  font-weight: bold;
  color: #333;
  width: 100px;
  text-align: right;
}

.form-select {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-select:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.submit-btn, .cancel-btn {
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  background-color: #31B310;
  color: white;
}

.submit-btn:hover {
  background-color: #2a990d;
}

.cancel-btn {
  background-color: #999;
  color: white;
}

.cancel-btn:hover {
  background-color: #777;
}
</style>